package dark

type NetResStr struct {
	Str
	HTTPS bool
	Err   error
}

func (str Str) AsNetRes(https bool, errs ...error) NetResStr {

	res := NetResStr{
		Str:   str,
		HTTPS: https,
	}
	if errs != nil {
		res.Err = errs[0]
	}

	return res
}

func (net NetResStr) GetHead(key Str) (val Str) {
	key = key.ToFirstUpper()
	isHeaderArea := false
	net.Str.EveryLine(func(lineno int, oldLine Str) {
		oldLine = oldLine.Trim()
		if lineno == 0 {
			isHeaderArea = true
			return
		}
		if isHeaderArea && oldLine == "" {
			isHeaderArea = false
		} else if isHeaderArea && oldLine.StartsWith(key.Str()+": ") {
			val = oldLine.Split(": ", 2).Last().Trim()
		}
	})
	return
}

func (net NetResStr) Status() (i int) {

	net.Str.EveryLine(func(lineno int, oldLine Str) {
		oldLine = oldLine.Trim()
		if lineno == 0 && oldLine.StartsWith("HTTP") {
			i = oldLine.Split(" ", 3).Nth(1).TryInt()
			return
		}
	})
	return
}

func (net NetResStr) Header() (keys Dict[Str]) {
	keys = make(Dict[Str])
	isHeaderArea := false
	net.Str.EveryLine(func(lineno int, oldLine Str) {
		oldLine = oldLine.Trim()
		if lineno == 0 {
			isHeaderArea = true
			return
		}
		if oldLine == "" && isHeaderArea {
			isHeaderArea = false
			return
		}
		if isHeaderArea && oldLine.In(":") {
			linekv := oldLine.ParseKV(true)
			keys = keys.Update(linekv)
		}
	})
	return
}

func (net NetResStr) Body() (body Str) {
	return net.Split("\r\n\r\n", 2).Last()
}

// func (net NetResStr) Elements() (eles Strs) {
// 	body := net.Body()
// 	body.Find(`(\<\w+\s*.+?\>)`)
// }
